<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>利用jquery ajax 向服务端上传json数据</title>
    <script src="/jquerydemo/script/jquery-3.3.1.js">
    </script>
    <script>
        $.fn.serializeObject = function() {
            var o = {"key":"value"};
            var a = this.serializeArray();
            $.each(a, function() {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [ o[this.name] ];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        };



        $().ready(function () {
            $(":button").click(function () {

                $.post({
                    url:"http://localhost:8080/reg",
                    data: {
                        username: $("#username").val(),
                        password: $("#password").val(),
                        age: $("#age").val()},
                    success:function (data, status, xhr) {
                        console.log(data)
                    }
                })
            })

            $("#submit").click(function () {
                $.post({
                    url:"http://localhost:8080/reg",
                    contentType : 'application/json',
                    data:JSON.stringify($("#form").serializeObject()),
                    success:function (data, status, xhr) {
                        console.log(data)
                    }
                })
            })
        })
    </script>
</head>
<body>
<h1>用户注册</h1>
<table>
    <tr><td>用户名：</td><td><input type="text" placeholder="您的用户名" id="username"/></td></tr>
    <tr><td>密&nbsp;&nbsp;码：</td><td><input type="password" id="password" placeholder="您的密码"/></td></tr>
    <tr><td>年&nbsp;&nbsp;龄：</td><td><input type="number" id="age"/></td></tr>
    <tr><td><input type="button"/></td></tr>
</table>
<br />


<form id="form">
    <tr><td>用户名：</td><td><input type="text" placeholder="您的用户名" name="username"/></td></tr>
    <tr><td>密&nbsp;&nbsp;码：</td><td><input type="password" name="password" placeholder="您的密码"/></td></tr>
    <tr><td>年&nbsp;&nbsp;龄：</td><td><input type="number" name="age"/></td></tr>
    <tr><td><input type="button" value="提交" id="submit"/></td></tr>
</form>
</body>
</html>